﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VPLink2014.Data;
using VPLink2014.Data.MesApplis;

namespace VPLink2013.Batch
{
    class Program
    {
        private static StringBuilder sbTrace;

        private static void SaveTrace(string fileName)
        {
            try
            {
                string strPath = System.Environment.CurrentDirectory + @"\" + fileName;
                System.IO.File.WriteAllText(strPath, sbTrace.ToString(), Encoding.UTF8);
                sbTrace = new StringBuilder();
            }
            catch (System.Exception exc)
            {
                Console.WriteLine(exc.Message);
                sbTrace.AppendLine(string.Format(" Exception : message {0} trace : {1}", exc.Message, exc.StackTrace));
            }
        }

        private static int getAppliIdByName(string applicationTitle)
        {
            int appId = -1;
            try
            {
                using (VPLinkLogConnection db = new VPLinkLogConnection())
                {
                    Application appDb = (from u in db.VplinkEntities.Applications
                                          where u.titre == applicationTitle
                                          select u).FirstOrDefault();
                    if (appDb != null)
                    {
                        appId = appDb.id;
                    }
                    else
                    {
                        Console.WriteLine("L'application {0} n'a pas été trouvé", applicationTitle);
                        sbTrace.AppendLine(string.Format("l'application {0} n' pas a été trouvé", applicationTitle));
                    }
                }
            }
            catch (Exception ex)
            {
                sbTrace.AppendLine(string.Format(" Exception : message {0} trace : {1}", ex.Message, ex.StackTrace));
            }
            return appId;
        }

        public static void AttachTeamToApplication(int teamType, string teamName, int applId)
        {
            List<VOApplication> listAppl = new List<VOApplication>();
            try
            {
                switch (teamType)
                {
                    case 1:
                        {
                            #region Direction
                            VODirectionMapper dir = new VODirectionMapper(teamName);
                            if (dir.direction != null)
                            {
                                Console.WriteLine("L'équipe {0} a été trouvé", teamName);
                                using (VPLinkLogConnection db = new VPLinkLogConnection())
                                {
                                    foreach (var app in db.VplinkEntities.GetDirectionApplications(teamName))
                                    {
                                        listAppl.Add(new VOApplication() { Id = app.id });
                                    }
                                }
                                if (!listAppl.Any(x => x.Id == applId))
                                {
                                    listAppl.Add(new VOApplication() { Id = applId });
                                    Console.WriteLine("Traitement...");
                                    dir.SetApplications(listAppl);
                                    Console.WriteLine("Ajout réussi.");
                                    sbTrace.AppendLine(string.Format("l'application a été rajouté à l'équipe {0}", teamName));
                                }
                                else
                                {
                                    Console.WriteLine("L'équipe {0} a déjà l'application", teamName);
                                    sbTrace.AppendLine(string.Format("L'équipe  {0} a déjà l'application", teamName));
                                }
                            }
                            else
                            {
                                Console.WriteLine("L'équipe {0} n'a pas été trouvé", teamName);
                                sbTrace.AppendLine(string.Format("l'équipe {0} n'a pas été trouvé", teamName));
                            }
                            break;
                            #endregion
                        }
                    case 2:
                        {
                            #region Departement
                            VODepartementMapper dept = new VODepartementMapper(teamName);
                            if (dept.departement != null)
                            {
                                Console.WriteLine("L'équipe {0} a été trouvé", teamName);
                                using (VPLinkLogConnection db = new VPLinkLogConnection())
                                {
                                    foreach (var app in db.VplinkEntities.GetDepartementApplications(teamName))
                                    {
                                        listAppl.Add(new VOApplication() { Id = app.id });
                                    }
                                }
                                if (!listAppl.Any(x => x.Id == applId))
                                {
                                    listAppl.Add(new VOApplication() { Id = applId });
                                    Console.WriteLine("Traitement...");
                                    dept.SetApplications(listAppl);
                                    Console.WriteLine("Ajout réussi.");
                                    sbTrace.AppendLine(string.Format("l'application a été rajouté à l'équipe {0}", teamName));
                                }
                                else
                                {
                                    Console.WriteLine("L'équipe {0} a déjà l'application", teamName);
                                    sbTrace.AppendLine(string.Format("L'équipe {0} a déjà l'application", teamName));
                                }
                            }
                            else
                            {
                                Console.WriteLine("L'équipe {0} n'a pas été trouvé", teamName);
                                sbTrace.AppendLine(string.Format("l'équipe {0} n' pas a été trouvé", teamName));
                            }
                            break;
                            #endregion
                        }
                    case 3:
                        {
                            #region Service
                            VOServiceMapper sce = new VOServiceMapper(teamName);
                            if (sce.service != null)
                            {
                                Console.WriteLine("L'équipe {0} a été trouvé", teamName);
                                using (VPLinkLogConnection db = new VPLinkLogConnection())
                                {
                                    foreach (var app in db.VplinkEntities.GetServiceApplications(teamName))
                                    {
                                        listAppl.Add(new VOApplication() { Id = app.id });
                                    }
                                }
                                if (!listAppl.Any(x => x.Id == applId))
                                {
                                    listAppl.Add(new VOApplication() { Id = applId });
                                    Console.WriteLine("Traitement...");
                                    sce.SetApplications(listAppl);
                                    Console.WriteLine("Ajout réussi.");
                                    sbTrace.AppendLine(string.Format("l'application a été rajouté à l'équipe {0}", teamName));
                                }
                                else
                                {
                                    Console.WriteLine("L'équipe  {0} a déjà l'application", teamName);
                                    sbTrace.AppendLine(string.Format("L'équipe  {0} a déjà l'application", teamName));
                                }
                            }
                            else
                            {
                                Console.WriteLine("L'équipe {0} n'a pas été trouvé", teamName);
                                sbTrace.AppendLine(string.Format("l'équipe {0} n' pas a été trouvé", teamName));
                            }
                            break;
                            #endregion
                        }
                    default: break;
                }
            }
            catch (Exception ex)
            {
                sbTrace.AppendLine(string.Format(" Exception : message {0} trace : {1}", ex.Message, ex.StackTrace));
            }
        }

        private static void AttachToAllTeams(string applicationsSettings)
        {
            string[] applicationNames = applicationsSettings.Split(';');
            List<string> directions = new List<string>();
            List<string> departemens = new List<string>();
            List<string> services = new List<string>();
            using (VPLinkLogConnection db = new VPLinkLogConnection())
            {
                db.VplinkEntities.AllDirections().ToList().ForEach(x => directions.Add(x.nom));
                db.VplinkEntities.AllDepartements().ToList().ForEach(x => departemens.Add(x.nom));
                db.VplinkEntities.AllServices().ToList().ForEach(x => services.Add(x.nom));
            }
            foreach (string appliName in applicationNames)
            {
                int appliId = getAppliIdByName(appliName);
                if (appliId != -1)
                {
                    try
                    {
                        foreach (string teamName in directions)
                        {
                            AttachTeamToApplication(1, teamName, appliId);
                        }
                        foreach (string teamName in departemens)
                        {
                            AttachTeamToApplication(2, teamName, appliId);
                        }
                        foreach (string teamName in services)
                        {
                            AttachTeamToApplication(3, teamName, appliId);
                        }
                    }
                    catch (Exception ex)
                    {
                        sbTrace.AppendLine(string.Format(" Exception : message {0} trace : {1}", ex.Message, ex.StackTrace));
                    }
                }
                else
                {
                    sbTrace.AppendLine(string.Format(" L'application {0} n'a pas été trouvé", appliName));
                }
            }
        }

        static void Main(string[] args)
        {
            sbTrace = new StringBuilder();

            string teamsSettings = ConfigurationSettings.AppSettings["teams"];
            string applicationsSettings = ConfigurationSettings.AppSettings["applications"];

            if (teamsSettings.Equals("all", StringComparison.CurrentCultureIgnoreCase))
            {
                AttachToAllTeams(applicationsSettings);
            }
            else
            {
                AttachToSpecificTeams(teamsSettings, applicationsSettings);
            }
            SaveTrace("trace.txt");
        }

        private static void AttachToSpecificTeams(string teamsSettings, string applicationsSettings)
        {
            string[] applicationNames = applicationsSettings.Split(';');
            string[] teams = teamsSettings.Split(';');

            foreach (string team in teams)
            {
                string teamTypeStr = team.Split(',')[0];
                string teamName = team.Split(',')[1];
                int teamType = Int32.Parse(teamTypeStr);

                foreach (string appliName in applicationNames)
                {
                    try
                    {
                        int appliId = getAppliIdByName(appliName);
                        if (appliId != -1)
                        {
                            AttachTeamToApplication(teamType, teamName, appliId);
                        }
                        else
                        {
                            sbTrace.AppendLine(string.Format(" L'application {0} n'a pas été trouvé", appliName));
                        }
                    }
                    catch (Exception ex)
                    {
                        sbTrace.AppendLine(string.Format(" Exception : message {0} trace : {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
        }
    }
}
